package com.uvnos4j.matilda.app;

import cn.hutool.extra.spring.SpringUtil;
import com.uvnos4j.matilda.commons.config.properties.SysProperties;
import com.uvnos4j.matilda.commons.services.schedule.ScheduleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * 项目启动完毕后开启需要执行的任务
 * <p>
 * Description:项目启动完毕后开启需要执行的任务
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda
 * @since 2020-04-06 17:08:00
 */
@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Autowired
    private SysProperties sysProperties;

    /**
     * 程序启动完毕后,需要执行的任务
     */
    @Override
    public void run(ApplicationArguments applicationArguments) {
        if (sysProperties.isInitDb()) {
            // 初始化数据库sql脚本文件
            runSqlBySpringUtils("sql/matilda.sql");
        }

        log.info(" >>>>>> 项目启动完毕, 开启 => 需要自启的任务 开始!");
        ScheduleService scheduledTaskService = SpringUtil.getBean(ScheduleService.class);
        scheduledTaskService.initAllTask();
        log.info(" >>>>>> 项目启动完毕, 开启 => 需要自启的任务 结束！");
    }

    /**
     * 执行sql脚本文件
     */
    public void runSqlBySpringUtils(String fileClassPath) {
        try {
            SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Connection conn = sqlSession.getConnection();
            ClassPathResource rc = new ClassPathResource(fileClassPath);
            EncodedResource er = new EncodedResource(rc, "utf-8");
            ScriptUtils.executeSqlScript(conn, er);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

}